<?php
namespace app\lmsx\home;

//use app\lmsx\model\User as UserModel;
//use app\lmsx\model\Category as CategoryModel;
use app\lmsx\model\Comment as CommentModel;
//use app\lmsx\model\Article as ArticleModel;
//use app\lmsx\model\Datum as DatumModel;
use app\lmsx\model\Message as MessageModel;
use think\Db;

/**
 * 小程序获取数据接口
 * @author lan
 */
class Api extends Index
{
    /**
     * 获取文章分类
     */
    public function get_category()
    {
        $param=request()->only('ident,city');
        $map=[];
        $map['status']=1;
        $map['ident']=$param['ident'];
        $list=Db::table('dp_lmsx_category')
            ->where($map)
            ->order('sort desc')
            ->field('id,name,cover')
            ->select();
        if($param['ident']=='article'){
            foreach ($list as $k=>&$v1){
//                if($v1['name']=='学子心事'){
//                    $v1['cover']='http://cdn.mogo.club/2d49da2b68e16b82b3e259a3a8f23ff6.png';
//                }
//                if($v1['name']=='家长智库'){
//                    $v1['cover']='http://cdn.mogo.club/c537ba0e37e120e352fe301200dbee0e.png';
//
//                }
                $v1['cover']='https://'.$_SERVER['SERVER_NAME'].get_file_path($v1['cover']);
            }
        }
        if($param['ident']=='direction'){//定向提分特殊处理
            if(empty($param['city'])){
                $param['city']=1;
            }
            $where=['ident'=>$param['ident'],'city'=>$param['city']];
            $list=Db::table('dp_lmsx_article')->where($where)->order('id desc')->select();
            foreach ($list as &$v){
               $v['cover']='https://'.$_SERVER['SERVER_NAME'].get_file_path($v['cover']);
               $v['title']=msubstr($v['title'],20,0);
               $v['content']=get_path_img($v['content']);
            }
        }

       //dump($list);die;
        //return json($list);
        return mogo_json($list);
    }



    /**
     * 获取科目分类datum
     */
    public function get_datum_cat()
    {
        $param=request()->only('grade');
        $map=['status'=>1,'name'=>$param['grade']];
        //$list=CategoryModel::where($map)->order('id,sort desc')->select();
        $list=Db::table('dp_lmsx_category')->where($map)->order('id,sort desc')->field('cid')->find();
        $list['cid']=explode(",",@$list['cid']);
        //$list=$row;dump($model);die;
        //return json($list);
        return mogo_json($list);
    }

    /**
     * 获取文章
     */
    public function get_article()
    {
        $param=request()->only('type_id,ident,openid,city');
        //ident文章唯一标识:article家长帮 information中高考资讯
        $map=[];
        if(!isset($param['ident'])){
            return mogo_json([],'缺失参数ident');
        }
        if(empty($param['type_id'])){
            if($param['ident']=='information'||$param['ident']=='discount'){
                $param['type_id']=0;
            }
        }
        if(!isset($param['city'])){
            $param['city']=1;
        }
        //dump($param['city']);die;
        if(!empty($param['type_id'])){
            $map['type_id']=$param['type_id'];
        }
        if(empty($param['type_id'])&&$param['ident']=='information'){
            $map['type_id']=$param['type_id'];
        }
        $map['ident']=$param['ident'];

        $map['city']=$param['city'];
        if($param['ident']=='information'&&$param['type_id']==1){
            unset($map['city']);
        }
        if($param['ident']=='article'){
            unset($map['city']);
        }
        if($param['ident']=='direction'){
            unset($map['type_id']);
        }
//        dump($map);die;
        $list=Db::table('dp_lmsx_article')
            ->where($map)
            ->field('id,cover,title,create_time,content')
            ->order('id desc')
            ->select();
        $list=$this->handle($list);
        //return json($list);
        return mogo_json($list);
    }
    /**
     * 获取文章详情
     */
    public function get_article_one()
    {
        $param=request()->only('id,openid');
        if(empty($param['id']))return mogo_error('未获取到文章id',404);
        $map=['id'=>$param['id']];
        $list=Db::table('dp_lmsx_article')
            ->where($map)
            ->field('title,create_time,content,ident')
            ->order('id desc')
            ->find();

        $list=$this->handle($list,'detail');
        if($list['ident']=='article' && isset($param['openid'])){//家长邦文章评论查询
            $list['comment']=Db::view('dp_lmsx_comment')
                ->view('dp_lmsx_user','avatar,nickname','dp_lmsx_user.openid=dp_lmsx_comment.openid')
                ->order('create_time')
                ->where(['dp_lmsx_comment.article_id'=>$param['id']])
                ->select();
            foreach ($list['comment'] as &$v){
                $v['create_time']=format_time($v['create_time'],'Y年m月d日');
            }
        }else{
            $list['comment']=[];
        }
        return mogo_json($list);
        //return json($list);
    }


    /**
     * 获取名校题库资料
     */
    public function get_datum()
    {
        $param=request()->param();
        //用户需要登录，获取用户身份及权限
        if(empty($param['openid'])){
            return mogo_error('用户未授权登录',401);
        }
       // $row=Db::table('dp_lmsx_user')->where(['openid'=>$param['openid']])->field('role,power')->find();
//        if($row['role']!=3 && $row['power']!=1){//不是老师
//            return mogo_error('您没有权限查看,请联系学校授权查看',404);
//        }
        $map=[];
        if(empty($param['grade'])){
            $param['grade']='初一';
        }
        if(empty($param['position'])){
            $param['position']=1;
        }
        $map['grade']=$param['grade'];
        $map['position']=$param['position'];
       // $map['grade']=$param['grade'];
        if(!empty($param['subject'])){
            $map['subject']=$param['subject'];
        }
        if($map['grade']=='高一'||$map['grade']=='高二'||$map['grade']=='高三'){
            unset($map['position']);
        }
        //获取资料,年级分类,科目
        $list=Db::table('dp_lmsx_datum')->where($map)->order('id desc')->select();
        $list=$this->handle($list);
//        dump($list);die;
        //return json($list);
        return mogo_json($list);
    }

    /**
     * 获取资料年级和科目
     */
    public function get_grade()
    {
        $data=request()->param();
        if(empty($data)){
            //获取年级
            $map=['ident'=>'datum','pid'=>0];
        }else{
            //获取科目
            $map=['ident'=>'datum','pid'=>$data['id']];
        }
        $list=Db::table('dp_lmsx_category')->where($map)->select();
       // return json($list);
        return mogo_json($list);
    }

    /**
     * 评论文章
     */
    public function comment_article()
    {
        //判断登录授权状态
        $data=request()->param();
        if(empty($data['openid'])){
            return mogo_error('未授权登录',401);
        }
        //禁用恶意留言用户
        $row_1=Db::table('dp_lmsx_user')->where(['openid'=>$data['openid']])->find();
        if(empty($row_1))return mogo_error('用户不存在',404);
        if($row_1['pull_black']==1)return mogo_error('您已被管理员禁止留言',404);
        //验证数据
        $result = $this->validate($data,'Comment');
        if($result!==true) return mogo_error($result,404);
        if($res=CommentModel::create($data))
        {
            $row=Db::view('dp_lmsx_comment')
                ->view('dp_lmsx_user','avatar,nickname','dp_lmsx_user.openid=dp_lmsx_comment.openid')
                ->where(['dp_lmsx_comment.id'=>$res['id']])
                ->find();
            $row['create_time']=format_time($row['create_time'],'Y年m月d日');
           // return json($res);
            return mogo_json($row,1);
        }else{
            return mogo_error($res,404);
        }
    }

    /**
     * 处理数据
     * @param array $list查询的数据内容
     * @param string $type数据分类，list表示列表页数据，detail表示详情页数据
     */
    public function handle($list,$type='list')
    {
        if(!empty($list)){
            if($type=='detail'){
                $list['title']=msubstr($list['title'],20,0);
//                $list['cover']='https://'.$_SERVER['SERVER_NAME'].get_file_path(@$list['cover']);
               // $list['content']=set_image_size(@$list['content']);
                $list['content']=get_path_img(@$list['content']);
                //$list['content']=set_image_size($list['content']);
                $list['create_time']=format_time($list['create_time'],'Y-m-d');
            }elseif($type=='list'){
                foreach ($list as $k=>&$v){
                    $v['title']=msubstr($v['title'],20,0);
                    $v['cover']='https://'.$_SERVER['SERVER_NAME'].get_file_path(@$v['cover']);
                    $v['img']=explode(",",@$v['img']);
                    $v['img']=get_files_path(@$v['img']);
                    foreach ($v['img'] as &$v1){
                        $v1='https://'.$_SERVER['SERVER_NAME'].$v1;
                    }
                   // $v['img']='https://'.$_SERVER['SERVER_NAME'].get_files_path(@$v['img']);
                    $v['content']=get_path_img(@$v['content']);
                    $v['document']='https://'.$_SERVER['SERVER_NAME'].get_file_path(@$v['document']);
                    $v['create_time']=format_time($v['create_time']);
                }
            }

        }
        return $list;
    }

    /**
     * 阿里云短信发送
     * @param $number 手机号码
     * @param $content  模板变量(e,g,Array('code'=>'123456'))
     * @return array    返回参数(e.g,Array('status'=>1,'msg'=>'发送成功','content'=>''))
     */
    public function send($number, $content,$openid)
    {
        $data =  plugin_action('AliyunSms','AliyunSms','sendSms',['phoneNumbers'=>$number,'templateParam'=>$content]);
        if ($data['Message'] != 'OK') {
            return ['msg' => $data['Message']];
        } else {
            $time=time();
            Db::table('dp_lmsx_user')->where(['openid'=>$openid])->update(['yzm_code'=>$content['code'],'yzm_time'=>$time]);
            return ['status' => 200, 'msg' => '发送成功'];
        }
    }

    /**
     * 短信验证
     * @param $mobile 手机号码
     * @param $type   验证类型(e.g,$type='login':登录)
     * @return array  参数说明(e.g,json(Array('status'=>0,'msg'=>'验证码错误','conten'=>'')))
     */
    public function verification($phone='',$openid='')
    {
        if (empty($phone)) {
            return json(['error' => '手机号码不存在'], 400);
        }
        if (empty($openid)) {
            return json(['error' => '用户不存在'], 400);
        }
        $row=Db::table('dp_lmsx_user')->where(['openid'=>$openid])->find();
        if ($row['yzm_time'] + 60 > time()) {
            return json(['error' => '一分钟内只能发送一次短信'], 400);
        }
        $code = rand(10000, 99999);
        $rel = $this->send($phone, array('code' => $code),$openid);
       // dump($rel);die;
        if ($rel['status'] == 200) {
            return json($rel);
            //return json( '验证码发送成功');
        }
        return mogo_error($rel['msg'],404);
    }

    /**
     * 绑定手机号
     */
    public function person()
    {
        $data=request()->param();
        if(empty($data['openid'])){
            return mogo_error('用户不存在',404);
        }
        //验证数据
        $result = $this->validate($data,'User.add');
        if($result!==true) return mogo_error($result,404);
        $row=Db::table('dp_lmsx_user')->where(['openid'=>$data['openid']])->find();
        if(empty($row)){
            return mogo_error('未授权登录',401);
        }
        if(!empty($row) && !empty($row['phone'])){
            return mogo_error('已经绑定手机号',404);
        }
        $num=Db::table('dp_lmsx_user')->where('phone','neq','')->count();
        $num=$num+1;
        $num='恭喜您成为第'.$num.'位尊贵会员';
        //判断code是否超时和是否正确|| $data['code'] == 'Mogo.club'
        if ($row['yzm_code'] == $data['code'] || $row['yzm_time'] + 600 >= time() ) {
            //绑定手机号码
            $res=Db::table('dp_lmsx_user')->where(['openid'=>$data['openid']])
                ->update(['name'=>$data['name'],'phone'=>$data['phone'],'role'=>$data['role'],'city'=>$data['city']]);
            return mogo_json($res,$num);
        } else {
            return mogo_error('验证码错误或已超时', 404);
        }
    }

    /**
     * 判断用户是否绑定手机号码
     */
    public function is_bind_phone()
    {
        $data=request()->param();
        if(empty($data['openid'])){
            return mogo_error('未授权登录',401);
        }
        $row=Db::table('dp_lmsx_user')->where(['openid'=>$data['openid']])->find();
        if(!empty($row) && !empty($row['phone'])){
            if($row['role']!=3 && $row['power']!=1){//不是老师
                return mogo_error('已经绑定手机号',1,2);
            }
            return mogo_error('已经绑定手机号',1,1);
        }
        return mogo_error('未绑定手机号',0,2);
    }

    /**
     * 留言
     */
    public function message()
    {
        $data=request()->param();
        if(empty($data['openid'])){
            return mogo_error('未授权登录',401);
        }
        //禁用恶意留言用户
        $row=Db::table('dp_lmsx_user')->where(['openid'=>$data['openid']])->find();
        if(empty($row))return mogo_error('用户不存在',404);
        if($row['pull_black']==1)return mogo_error('您已被管理员禁止留言',404);
        //验证
        if($res=MessageModel::create($data)){
            return mogo_json($res,'留言成功');
        }else{
            return mogo_json($res,'留言失败');
            //  return json(['error'=>0,'msg'=>'留言失败']);
        }
    }

    /**
     * 显示留言
     */
    public function get_message(){
       $list=Db::table('dp_lmsx_message')->where(['back_id'=>0])->order('create_time')->select();
       $list=Db::view('dp_lmsx_message')
           ->view('dp_lmsx_user','avatar,nickname name','dp_lmsx_user.openid=dp_lmsx_message.openid')
           ->order('dp_lmsx_message.create_time')
           ->select();
       //dump($list);die;
       foreach ($list as &$v){
           $v['create_time']=format_time($v['create_time'],'m-d H:i');
           $m=Db::view('dp_lmsx_message')
               ->view('dp_admin_user','avatar backavatar,nickname backname','dp_admin_user.id=dp_lmsx_message.openid')
               ->where('dp_lmsx_message.back_id',$v['id'])
               ->order('dp_lmsx_message.create_time')
               ->select();
           foreach ($m as &$v1){
               $v1['create_time']=format_time($v1['create_time'],'m-d H:i');
               $v1['backavatar']='https://'.$_SERVER['SERVER_NAME'].get_avatar($v1['backavatar']);
           }
           //dump($m);die;
           $v['back']=$m;
       }
        //dump($list);die;
        return mogo_json($list,'200');
      // return json(['error'=>1,'data'=>$list]);
    }

    /**
     * 一键导航接口
     */
    public function get_maps(){
        $param=request()->param();
        $map=true;
        if(!empty($param['position'])){
            $str='%'.$param['position'].'%';
            //dump($str);die;
            //$map="'position','like',$str";
            $map=['position'=>['like',[$str]]];
        }

        $list=Db::table('dp_lmsx_maps')->where($map)->order('sort desc,id desc')->select();
        foreach ($list as &$v){
            $m=explode(",",$v['city']);
            //dump($m);die;
            $v['jing_du']=@$m[0];
            $v['wei_du']=@$m[1];
        }
        return mogo_json($list);
    }

    /**
     * 获取广告图
     */
    public function get_banner(){
        $param=request()->only('category');
        $map=[];
        if(!empty($param['category'])){
            $map['category']=$param['category'];
            $map['status']=1;
        }
        $list=Db::table('dp_lmsx_banner')->where($map)->order('sort desc')->limit(4)->select();
        foreach ($list as &$v){
            $v['img']='https://'.$_SERVER['SERVER_NAME'].get_file_path($v['img']);
        }
        return mogo_json($list,1);
    }

    /**
     * 获取求助通道的背景图
     */
    public function get_qztd()
    {
        $id=config('ask_for_help');
        $id='https://'.$_SERVER['SERVER_NAME'].get_file_path($id);
        return json($id);
    }
}